package com.xiashitech.agent.db.dao.extload;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.db.DbUtil;
import cn.hutool.db.StatementUtil;
import cn.hutool.db.sql.SqlExecutor;
import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.db.extload.LocalDataSource;
import com.xiashitech.agent.db.entity.UserPermission;
import com.xiashitech.agent.utils.XSUtil;

import java.sql.*;

public class CommonDao {

    public void executeDDL() {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = LocalDataSource.getDS().getConnection();
            DatabaseMetaData metaData = conn.getMetaData();
            ResultSet tables = metaData.getTables(null, null, UserPermission.TABLE_NAME, null);
            //execute only on the first initialization
            if (tables.next()){
                return;
            }
            String ddlSQL = ResourceUtil.readUtf8Str("xs.agent.db/agent-ddl.sql");
            ps = StatementUtil.prepareStatement(conn, ddlSQL);
            SqlExecutor.executeUpdate(ps);
            XSUtil.debug("Agent-DB initialized successfully.");
        } catch (SQLException e) {
            XSUtil.debug("Agent-DB initialized failed. {}", e.getMessage());
            StartConfig.throwableStackPrinter(e);
        }finally {
            DbUtil.close(ps);
            DbUtil.close(conn);
        }
    }

}
